package com.roomio.web;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.roomio.domain.GroupTransaction;
import com.roomio.domain.Transaction;
import com.roomio.domain.UserTransaction;
import com.roomio.service.GroupInfoService;
import com.roomio.service.TransactionsService;


@RequestMapping("/transactionses")
@Controller
public class TransactionController extends BaseSpringController {
	
	@Autowired
	private GroupInfoService groupInfoService; 
	
	@Autowired
	private TransactionsService transactionService; 
	
	//TODO: need setting page
	//setting max number of record
	@RequestMapping(value="", produces = "text/html")
    public String listGroupTransaction(@RequestParam(value = "page", required = false) Integer page, @RequestParam(value = "size", required = false) Integer size, Model uiModel) {
     
            uiModel.addAttribute("transactionses", transactionService.findAllGroupTransactions(new Long(1)));
        return "transactionses/list";
    }
	
	@RequestMapping(value="transactionses/user/create", method = RequestMethod.POST, produces = "text/html")
    public String addUserTransaction(@Valid UserTransaction transaction, BindingResult bindingResult, Model uiModel, HttpServletRequest httpServletRequest) {
        if (bindingResult.hasErrors()) {
            populateEditForm(uiModel, transaction);
            return "transactionses/user/create";
        }
        uiModel.asMap().clear();
        transaction.setOwner(getCurrentUser());
        transactionService.saveUserTransaction(transaction);
        return "redirect:/transactionses/user" + encodeUrlPathSegment(transaction.getId().toString(), httpServletRequest);
    }
	
	@RequestMapping(value="transactionses/owner/create", method = RequestMethod.POST, produces = "text/html")
    public String addGroupTransaction(@Valid GroupTransaction transaction, BindingResult bindingResult, Model uiModel, HttpServletRequest httpServletRequest) {
        if (bindingResult.hasErrors()) {
            populateEditForm(uiModel, transaction);
            return "transactionses/owner/create";
        }
        uiModel.asMap().clear();
        transaction.setOwner(getCurrentUser());
        transactionService.saveGroupTransaction(transaction);
        return "redirect:/transactionses/group" + encodeUrlPathSegment(transaction.getId().toString(), httpServletRequest);
    }
	
	 void populateEditForm(Model uiModel, Transaction transaction) {
	        uiModel.addAttribute("transaction", transaction);
	    }
    

}
